from flask import request


class ValidationError(Exception):
    def __init__(self, message, status_code=400):
        super().__init__()
        self.message = message
        self.status_code = status_code


class RequestParser:
    def __init__(self):
        self.args = []

    def add_argument(self, name, type=str, required=False, help=None):
        self.args.append({
            'name': name,
            'type': type,
            'required': required,
            'help': help
        })

    def parse_args(self):
        # 检查JSON格式
        if not request.is_json:
            raise ValidationError("Request must be JSON format", 400)
        data = request.get_json()
        parsed = {}

        for arg in self.args:
            name = arg['name']
            value = data.get(name)
            # 处理必填校验
            if arg['required'] and value is None:
                raise ValidationError(f"{name} is required", 400)

            # 处理类型校验
            if value is not None:
                try:
                    parsed[name] = arg['type'](value)
                except (TypeError, ValueError):
                    raise ValidationError(
                        f"{name} must be {arg['type'].__name__}",
                        400
                    )
            else:
                parsed[name] = None
        return parsed
